package com.bookstore.service.impl;



import com.bookstore.dao.UserDao;
import com.bookstore.entity.User;
import com.bookstore.factory.DaoFactory;
import com.bookstore.service.UserService;
import com.bookstore.utils.DataDictionary;
import com.bookstore.utils.GudgeType;

import java.util.List;

public class UserServiceImpl implements UserService {
    //用户数据访问层实例
    UserDao userDao= DaoFactory.getUserDao();

    @Override
    public int register(User user) {
        if (GudgeType.isNull(user.getUsername(),user.getPassword(),user.getRole())){
            //用户名或密码或状态不能为空
            return DataDictionary.DATAISNULL;
        }
        int result=userDao.insertUser(user);
        if (result>0){
            return 1;
        }
        return DataDictionary.SQLREGISTERERROR;
    }

    @Override
    public User LoginUser(String username, String password) {
        if (GudgeType.isNull(username,password)){
            //用户名或密码不能为空
        }
        User user = userDao.queryNameAndPassword(username, password);
        if (!GudgeType.isNull(user)){
            if (user.getRole()==0){
                return user;
            }
            else {
                return (User) DataDictionary.NOMENEGERACCESS;
            }
        }
        return (User) DataDictionary.SQLQUERYERROR;
    }

    @Override
    public User loginMeneger(String username, String password) {
        if (GudgeType.isNull(username,password)){
            //用户名或密码不能为空
        }
        User user = userDao.queryNameAndPassword(username, password);
        if (!GudgeType.isNull(user)){
            if (user.getRole()==1){
                return user;
            }
            else {
                return (User) DataDictionary.NOMENEGERACCESS;
            }
        }
        return (User) DataDictionary.SQLQUERYERROR;
    }

    @Override
    public int cancel(int userId) {
        return 0;
    }

    @Override
    public List<User> showAllUser() {
        return userDao.queryAllUser();
    }

    @Override
    public User queryUserById(Long userId) {
        if (GudgeType.isNull(userId)){
            return (User) DataDictionary.SQLQUERYERROR;
        }
        return userDao.queryUserId(userId);
    }

    @Override
    public int deleteUser(Long userId) {
        if (GudgeType.isNull(userId)){
            return DataDictionary.DATAISNULL;
        }
        User user = userDao.queryUserId(userId);
        if (user==null||user.getState()==0){
            return DataDictionary.DATAISNULL;
        }
        return userDao.deleteUser(userId);
    }

    @Override
    public int resetPwd(User user) {
        if (GudgeType.isNull(user)){
            return DataDictionary.DATAISNULL;
        }
        return userDao.updateUser(user);
    }
}
